package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author mrchen
 * @date 2022/1/12 11:45
 */
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDTO dto) {
        // 1. 参数校验
        // 2. 远程查询行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到行为实体数据");
        }
        // 3. 根据行为实体id查询是否搜索过关键词
        ApUserSearch one = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("keyword").is(dto.getSearchWords())), ApUserSearch.class);
        // 4. 修改时间
        if(one != null){
            one.setCreatedTime(new Date());
        }else {
            one = new ApUserSearch();
            one.setEntryId(behaviorEntry.getId());
            one.setKeyword(dto.getSearchWords());
            one.setCreatedTime(new Date());
        }
        // 5. 添加到mongo 搜索记录种
        mongoTemplate.save(one);
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        // 1. 校验参数
        int size = 10;
        ApUser user = AppThreadLocalUtils.getUser();
        // 2. 查询对应行为实体
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到行为实体数据");
        }
        // 3. 根据行为实体id  查询历史记录  按照时间降序排序  查10条
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size), ApUserSearch.class);
        // 4. 返回历史记录
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }
}